package com.hxkcloud.patient.activitys;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.hxkcloud.patient.R;
import com.hxkcloud.patient.adapter.HistoryRecordAdapter;
import com.hxkcloud.patient.adapter.MainPageListAdapter;
import com.hxkcloud.patient.beans.DisabilityListBean;
import com.hxkcloud.patient.beans.DoctorGroupBean;
import com.hxkcloud.patient.beans.DoctorPatientBean;
import com.hxkcloud.patient.beans.DoctorPatientGroupBean;
import com.hxkcloud.patient.beans.DoctorPatientListBean;
import com.hxkcloud.patient.beans.DoctorPatientResultBean;
import com.hxkcloud.patient.beans.resultbeans.ObjectResultBean;
import com.hxkcloud.patient.config.UrlConfig;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.ImageOptionUtils;
import com.hxkcloud.patient.utils.SharedPreferenceUtil;
import com.hxkcloud.patient.views.CircleImageView;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * ProjectName: YJHCuzhong
 * PackageName: com.yjhcloud.patient.activitys
 * Description:
 * Create by Ray.
 * Date: 2016/10/11 15:22
 */
public class SearchPatientActivity extends BaseActivity implements View.OnClickListener,MainPageListAdapter.ResultSelectedListener{

    private LinearLayout wholeLayout;
    private EditText searchET;//搜索输入框
    private TextView cancelTV;//取消
    private TextView recordTV;//历史记录
    private ListView recordListView;//历史记录列表
    private HistoryRecordAdapter recordAdapter;

    private LinkedList<String> recordList;

    private SwipeRefreshLayout swipeRefreshLayout;
    private ExpandableListView expandableListView;
    private MyExpandableListViewAdapter expandAdapter;

    private RecyclerView recyclerView;
    private MainPageListAdapter adapter;
    private List<DoctorPatientBean> patientListDatas;

    private List<DoctorPatientGroupBean> group_list;
    private List<List<DoctorPatientBean>> item_list;

    private LinearLayout resultLayout;


    private TextView countTV;


    private List<DoctorGroupBean> groupBeans;

    private ObjectResultBean<DisabilityListBean> disabilityResultBean;//残疾程度返回值

    private ObjectResultBean<DoctorPatientResultBean> resultBean;//返回结果集

    private List<DoctorPatientGroupBean> patientGroupBeans;//分组列表
    private DoctorPatientListBean patientListBean;//非分组列表

    private String patientCount = "";//非分组人数

    private String keyword="";



    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_DOCTORPATIENTLIST_SUCCESS:
                dismisssLoading();
                if(msg.obj !=null){
                    resultBean = (ObjectResultBean<DoctorPatientResultBean>) msg.obj;
                    if(resultBean.getData().getFzList()!=null){
                        patientGroupBeans = resultBean.getData().getFzList();
                        group_list.clear();
                        item_list.clear();
                        if(patientGroupBeans!=null && patientGroupBeans.size()>0){
                            expandableListView.setVisibility(View.VISIBLE);
                            for(int i = 0;i<patientGroupBeans.size();i++){
                                group_list.add(patientGroupBeans.get(i));
                                item_list.add(patientGroupBeans.get(i).getPatients());
                            }
                            expandableListView.setAdapter(expandAdapter);
                            setListViewHeight(expandableListView);
                        }else{
                            expandableListView.setVisibility(View.GONE);
                        }
                    }
                    if(resultBean.getData().getFfzMap()!=null){
                        if(patientListDatas!=null&&patientListDatas.size()>0){
                            patientListDatas.clear();
                        }
                        patientListBean = resultBean.getData().getFfzMap();
                        patientCount = patientListBean.getPatientCount()+"";
                        countTV.setText(patientCount+getResources().getString(R.string.mainpage_text_person));
                        patientListDatas = patientListBean.getPatients();
                        if(patientListDatas!=null && patientListDatas.size()>0){
                            recyclerView.setVisibility(View.VISIBLE);
                            adapter = new MainPageListAdapter(this, patientListDatas,this, screenWidth);
                            recyclerView.setAdapter(adapter);
//                          adapter.setData(patientListDatas);
                        }else{
                            countTV.setText("0" + getResources().getString(R.string.mainpage_text_person));
                            recyclerView.setVisibility(View.GONE);
                        }

                    }

                }

                break;
            case MessageCode.NETWORKCODE_DOCTORPATIENTLIST_FAILURE:
                dismisssLoading();
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                }

                break;

        }

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout_searchpatient);
        patientListDatas = new ArrayList<>();
        recordList = new LinkedList<String>();
        if (SharedPreferenceUtil.getDoctorPatientHistoryKeywords(mContext) != null) {
            String list = SharedPreferenceUtil.getDoctorPatientHistoryKeywords(mContext);
            if (list != null && !"".equals(list)) {
                String list1 = list.substring(1, list.length() - 1);
                String[] arr = list1.split(",");
                System.out.println(arr[0]);
                int length = arr.length;
                if (length <= 10) {
                    for (int i = 0; i < length; i++) {
                        recordList.addFirst(arr[(length - 1) - i].trim());
                    }
                }

            }
        }
        initView();
        initData();
        initListener();
    }

    @Override
    protected void initView() {

        wholeLayout = (LinearLayout) findViewById(R.id.searchpatient_layout_whole);
        setTitlePadding(wholeLayout);
        searchET = (EditText) findViewById(R.id.searchpatient_et_search);
        cancelTV = (TextView) findViewById(R.id.searchpatient_tv_cancel);
        recordTV = (TextView) findViewById(R.id.searchpatient_tv_history);
        recordListView = (ListView) findViewById(R.id.searchpatient_lv_record);
        recordAdapter = new HistoryRecordAdapter(this, recordList);
        recordListView.setAdapter(recordAdapter);


        countTV = (TextView) findViewById(R.id.mainpage_tv_count);
        resultLayout = (LinearLayout) findViewById(R.id.searchpatient_layout_result);


//        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.mainpage_swiperefresh);
        expandableListView = (ExpandableListView) findViewById(R.id.mainpage_expandableListView);
        expandableListView.setDividerHeight(0);


//        swipeRefreshLayout.setEnabled(true);
//        swipeRefreshLayout.setOnRefreshListener(this);
//        swipeRefreshLayout.setProgressViewOffset(true, -20, 100);

        recyclerView = (RecyclerView) findViewById(R.id.mainpage_recyclerView);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(mLayoutManager);
//        adapter = new MainPageListAdapter(this, patientListDatas,this, screenWidth);
//        recyclerView.setAdapter(adapter);


    }

    @Override
    protected void initListener() {

        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
                Intent iP = new Intent(mContext, DpatientInfoActivity.class);
                iP.putExtra("patientid", item_list.get(groupPosition).get(
                        childPosition).getPatientId()+"");
                iP.putExtra("name", item_list.get(groupPosition).get(
                        childPosition).getName());
                iP.putExtra("age", item_list.get(groupPosition).get(
                        childPosition).getAge()+getResources().getString(R.string.usermanger_text_age));
                if("0".equals(item_list.get(groupPosition).get(
                        childPosition).getSex())){
                    iP.putExtra("sex", getResources().getString(R.string.male));
                }else{
                    iP.putExtra("sex", getResources().getString(R.string.female));
                }
                startActivity(iP);
                return true;
            }
        });

        cancelTV.setOnClickListener(this);

        searchET.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                // TODO Auto-generated method stub
                if (actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_ACTION_SEND || actionId == EditorInfo.IME_ACTION_SEARCH ||
                        (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)
                        || actionId == EditorInfo.IME_ACTION_DONE) {

                    String keywords = searchET.getText().toString().trim();

                    if (keywords == null || "".equals(keywords)) {
                        toastMsg(getResources().getString(R.string.pleaseinputcontent));
                        // 提示为空
                    } else {
                        keyword = keywords;
                        if (recordList.size() == 10) {
                            recordList.remove(recordList.size() - 1);
                        }
                        recordList.addFirst(keywords);
                        SharedPreferenceUtil.setDoctorPatientHistoryKeywords(mContext, recordList);
                        recordAdapter.notifyDataSetChanged();
                        recordTV.setVisibility(View.GONE);
                        recordListView.setVisibility(View.GONE);
                        resultLayout.setVisibility(View.VISIBLE);
                        YiJiaHuNetWorkUtils.getDocotrPatientList("-1", "", "", keyword, handler);
                    }
                    return false;
                }
                return false;
            }
        });

        recordListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                keyword = recordList.get(position);
                searchET.setText(recordList.get(position));
                recordTV.setVisibility(View.GONE);
                recordAdapter.notifyDataSetChanged();
                recordListView.setVisibility(View.GONE);
                resultLayout.setVisibility(View.VISIBLE);
                YiJiaHuNetWorkUtils.getDocotrPatientList("-1", "", "", keyword, handler);
            }
        });

    }

    @Override
    protected void initData() {

        //分组数据
        group_list = new ArrayList<DoctorPatientGroupBean>();
        item_list = new ArrayList<List<DoctorPatientBean>>();
        expandAdapter = new MyExpandableListViewAdapter(SearchPatientActivity.this);

    }




    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.searchpatient_tv_cancel:
                recordAdapter.notifyDataSetChanged();
                finish();
                break;
        }
    }


    @Override
    public void onSelected(String type, int position) {
        if ("item".equals(type)) {
            Intent iP = new Intent(mContext, DpatientInfoActivity.class);
            iP.putExtra("patientid", patientListDatas.get(
                    position).getPatientId() + "");
            iP.putExtra("name", patientListDatas.get(
                    position).getName());

            if(patientListDatas.get(
                    position).getAge() == 0 || "".equals(patientListDatas.get(
                    position).getAge()+"")){
                iP.putExtra("age", "<1" + getResources().getString(R.string.usermanger_text_age));
            }else{
                iP.putExtra("age", patientListDatas.get(
                        position).getAge() + getResources().getString(R.string.usermanger_text_age));;
            }
            if ("0".equals(patientListDatas.get(
                    position).getSex())) {
                iP.putExtra("sex", getResources().getString(R.string.male));
            } else {
                iP.putExtra("sex", getResources().getString(R.string.female));
            }
            startActivity(iP);
        }

    }


    //用过ListView的人一定很熟悉，只不过这里是BaseExpandableListAdapter
    class MyExpandableListViewAdapter extends BaseExpandableListAdapter {

        private Context context;

        public MyExpandableListViewAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getGroupCount() {
            return group_list.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return item_list.get(groupPosition).size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return group_list.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return item_list.get(groupPosition).get(childPosition);
        }

        public void onGroupCollapsed(int groupPosition) {
            setListViewHeight(expandableListView);
        }

        public void onGroupExpanded(int groupPosition) {
            setListViewHeight(expandableListView);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            GroupHolder groupHolder = null;
            if (convertView == null) {
                convertView = (View) getLayoutInflater().from(context).inflate(
                        R.layout.expendlist_group, null);
                groupHolder = new GroupHolder();
                groupHolder.groupLayout = (LinearLayout) convertView.findViewById(R.id.expandlist_layout_groupitem);
                groupHolder.week = (TextView) convertView.findViewById(R.id.expandlist_tv_week);
                groupHolder.date = (TextView) convertView.findViewById(R.id.expandlist_tv_date);
                groupHolder.patientCount = (TextView) convertView.findViewById(R.id.expandlist_tv_count);
                groupHolder.img = (ImageView) convertView
                        .findViewById(R.id.img);

                convertView.setTag(groupHolder);
            } else {
                groupHolder = (GroupHolder) convertView.getTag();
            }
            groupHolder.week.setText(group_list.get(groupPosition).getWeek());
            groupHolder.date.setText(group_list.get(groupPosition).getDate());
            groupHolder.patientCount.setText(group_list.get(groupPosition).getPatientCount() + "人");
            groupHolder.img.setBackgroundResource(R.mipmap.mainpage_list_arrow_pre);

            if(isExpanded){
                groupHolder.img.setBackgroundResource(R.mipmap.mainpage_list_arrow);
                groupHolder.groupLayout.setBackgroundColor(mContext.getResources().getColor(R.color.expandlist_item_color));
            }else{
                groupHolder.img.setBackgroundResource(R.mipmap.mainpage_list_arrow_pre);
                groupHolder.groupLayout.setBackgroundColor(mContext.getResources().getColor(R.color.white));
            }

            return convertView;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {
            ItemHolder itemHolder = null;
            if (convertView == null) {
                convertView = (View) getLayoutInflater().from(context).inflate(
                        R.layout.expendlist_item, null);
                itemHolder = new ItemHolder();
                itemHolder.name = (TextView) convertView.findViewById(R.id.expandlistitem_tv_name);
                itemHolder.age = (TextView) convertView.findViewById(R.id.expandlistitem_tv_age);
                itemHolder.sex = (TextView) convertView.findViewById(R.id.expandlistitem_tv_sex);
                itemHolder.disability = (TextView) convertView.findViewById(R.id.expandlistitem_tv_disability);
                itemHolder.userIcon = (CircleImageView) convertView.findViewById(R.id.expandlistitem_iv_img);
                itemHolder.bottomView = (View) convertView.findViewById(R.id.expandlistitem_bottomView);
                convertView.setTag(itemHolder);
            } else {
                itemHolder = (ItemHolder) convertView.getTag();
            }
            itemHolder.name.setText(item_list.get(groupPosition).get(
                    childPosition).getName());
            itemHolder.age.setText(item_list.get(groupPosition).get(
                    childPosition).getAge() + getResources().getString(R.string.usermanger_text_age));
            if ("0".equals(item_list.get(groupPosition).get(
                    childPosition).getSex())) {
                itemHolder.sex.setText(getResources().getString(R.string.male));
            } else {
                itemHolder.sex.setText(getResources().getString(R.string.female));
            }

//            itemHolder.disability.setText(item_list.get(groupPosition).get(
//                    childPosition).getDisabilityName());
//            if ("".equals(item_list.get(groupPosition).get(
//                    childPosition).getDisabilityName())) {
//                itemHolder.disability.setVisibility(View.INVISIBLE);
//            } else {
//                itemHolder.disability.setVisibility(View.VISIBLE);
//            }

            DisplayImageOptions option = null;
            long dateBegin = (new Date(Long.valueOf(item_list.get(groupPosition).get(
                    childPosition).getAge()))).getTime();
            long dateNow = (new Date()).getTime();
            long age = (dateNow - dateBegin) / 1000 / 60 / 60 / 24 / 365;
            if (item_list.get(groupPosition).get(
                    childPosition).getSex().equals("0")) {//male
                if (age > 49) {
                    option = ImageOptionUtils.getInstance().getMan50HeadOptions();
                } else {
                    option = ImageOptionUtils.getInstance().getMan20HeadOptions();
                }
            } else {//female
                if (age > 49) {
                    option = ImageOptionUtils.getInstance().getWoman50HeadOptions();
                } else {
                    option = ImageOptionUtils.getInstance().getWoman20HeadOptions();
                }
            }
            if(item_list.get(groupPosition).get(
                    childPosition).getHeadImage().startsWith("image")){
                imageLoader.displayImage(UrlConfig.image_host+item_list.get(groupPosition).get(
                        childPosition).getHeadImage(), itemHolder.userIcon, option);
            }else{
                imageLoader.displayImage(item_list.get(groupPosition).get(
                        childPosition).getHeadImage(),itemHolder.userIcon, option);
            }

            if (isLastChild) {
                itemHolder.bottomView.setVisibility(View.GONE);
            } else {
                itemHolder.bottomView.setVisibility(View.VISIBLE);
            }

            String selfCare = item_list.get(groupPosition).get(
                    childPosition).getDisabilityName();
            if(TextUtils.isEmpty(selfCare)){
                itemHolder.disability.setVisibility(View.INVISIBLE);
            } else if (selfCare.equals(mContext.getResources().getString(R.string.selfcare_level1))){
                itemHolder.disability.setText(mContext.getResources().getString(R.string.degaree_text_level1));
                itemHolder.disability.setBackgroundResource(R.drawable.bg_text_line_level1);
                itemHolder.disability.setTextColor(mContext.getResources().getColor(R.color.color_level1));
            }else if(selfCare.equals(mContext.getResources().getString(R.string.selfcare_level2))) {
                itemHolder.disability.setVisibility(View.VISIBLE);
                itemHolder.disability.setText(mContext.getResources().getString(R.string.degaree_text_level2));
                itemHolder.disability.setBackgroundResource(R.drawable.bg_text_line_level2);
                itemHolder.disability.setTextColor(mContext.getResources().getColor(R.color.color_level2));
            }else if(selfCare.equals(mContext.getResources().getString(R.string.selfcare_level3))) {
                itemHolder.disability.setVisibility(View.VISIBLE);
                itemHolder.disability.setText(mContext.getResources().getString(R.string.degaree_text_level3));
                itemHolder.disability.setBackgroundResource(R.drawable.bg_text_line_level3);
                itemHolder.disability.setTextColor(mContext.getResources().getColor(R.color.color_level3));
            }else if(selfCare.equals(mContext.getResources().getString(R.string.selfcare_level4))) {
                itemHolder.disability.setVisibility(View.VISIBLE);
                itemHolder.disability.setText(mContext.getResources().getString(R.string.degaree_text_level4));
                itemHolder.disability.setBackgroundResource(R.drawable.bg_text_line_level4);
                itemHolder.disability.setTextColor(mContext.getResources().getColor(R.color.color_level4));
            }

            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

    }

    class GroupHolder {
        public LinearLayout groupLayout;
        public TextView week;
        public TextView date;
        public TextView patientCount;
        public ImageView img;
    }

    class ItemHolder {
        public CircleImageView userIcon;
        public TextView name;
        public TextView age;
        public TextView sex;
        public TextView disability;
        public View bottomView;
    }



    private void setListViewHeight(ExpandableListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        int totalHeight = 0;
        int count = listAdapter.getCount();
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }

}
